import axios from "axios";
import qs from "qs";

console.log("axios", axios.defaults.timeout);

let baseUrl = "";

/*
 * 设置超时时间
 * 设置是否允许跨域携带身份凭证
 */
axios.defaults.timeout = 12000;
axios.defaults.baseUrl = baseUrl;
axios.defaults.withCredentials = true;

axios.defaults.headers["Authorization"] = "eyJKV1QiOiJKV1QiLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiaWF0IjoxNjM2NDI4MDMxLCJqdGkiOiIzMmM0Y2JmYTZlOGE0Y2M4YjRkMDM1ODk3YjI5NzAyZiJ9.FLJnRiaw1oz8qgPZsuq8pINHeJNRf87bGE2uqN2akgc";
axios.defaults.transformRequest = (data) => {
  qs.stringify(data);
};

// 请求拦截
axios.interceptors.request.use(
  (config) => {
    // 设置 token
    // let token = localStorage.getItem('token');
    // token && (config.headers.Authorization = token);
    return config;
  },
  (error) => {
    //请求失败时执行
    return window.Primise.reject(error);
  }
);

// 响应拦截
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 错误拦截
    // let { response } = error;
    // if (response) {
    //     switch (response.status) {
    //         case 401://权限问题,提示未登录或无权限等；
    //             break;
    //         case 403://服务器拒绝执行 （token过期）
    //             break;
    //         case 404://找不到页面
    //             break;
    //     }
    // } else {
    //     if (!window.navigator.onLine) {
    //         //断网处理：跳转断网页面/提示网络错误等等
    //         return;
    //     }
    //     return Promise.reject(error)
    // }
    return window.Promise.reject(error);
  }
);

/**
  * GET
  * @param url
  * @param params
  * @returns {Promise}
  */
export const Get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
  * POST
  * @param url
  * @param params
  * @returns {Promise}
  */
export const Post = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
  * DELETE
  * @param url
  * @param params
  * @returns {Promise}
  */
export const Delete =  (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * PUT
 * @param url
 * @param params
 * @returns {Promise}
 */
export const Put = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .put(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};